package cn.jinjimi.app.custom.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import cn.jinjimi.base.util.AndroidUtils;
import cn.jinjimi.base.util.Lunar;
import cn.jinjimi.base.util.StringUtils;
import cn.jinjimi.base.util.ToastUtils;
import cn.jinjimi.app.R;
import cn.jinjimi.app.bean.Constants;
import cn.jinjimi.app.bean.BundleKey;
import cn.jinjimi.app.controller.CustomerController;
import cn.jinjimi.app.controller.event.PhotosListEvent;
import cn.jinjimi.app.custom.entity.Custom;
import cn.jinjimi.app.custom.ui.adapter.CustomInfoPhotoPreViewAdapter;
import cn.jinjimi.app.custom.ui.view.CustomInfoPhoneView;
import cn.jinjimi.app.entity.PhotoInfo;
import cn.jinjimi.app.store.entity.custom.ContactInfo;
import cn.jinjimi.app.main.dialog.DatePickerDialog;
import cn.jinjimi.app.main.extend.ToolBarCommonActivity;
import cn.jinjimi.app.util.PhotoUtils;
import cn.jinjimi.app.util.ToastUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Calendar;
import java.util.List;

/**
 * Created by Roy
 * Date: 16/6/6
 */
public class CustomInfoActivity extends ToolBarCommonActivity implements AdapterView.OnItemClickListener {

    private Custom mCustom = null;

    private ImageView imgAvatar;
    private TextView tvName;
    private TextView tvGender;
    private TextView tvBirthday;

    private LinearLayout mPhoneLayout = null;

    private TextView tvIdCard;
    private TextView tvIdCode;
    private ImageView imgIdVisible;
    private boolean isShowIdCode;
    private TextView tvEmail;

    private TextView tvStatus;
    private TextView tvLevel;
    private TextView tvArea;
    private TextView tvAddr;
    private TextView tvRemark;

    private GridView mGridView;
    private CustomInfoPhotoPreViewAdapter mAdapter;

    public static void launch(Context startActivity, Custom custom) {
        Intent intent = new Intent(startActivity, CustomInfoActivity.class);
        intent.putExtra(BundleKey.PARAM_CUSTOM, custom);
        startActivity.startActivity(intent);
    }

    @Override
    protected void beforeInitView() {
        setContentView(R.layout.activity_custom_info);
        setTitle(getString(R.string.custom_info));
        setRightText(R.string.edit);
    }

    @Override
    protected void initial() {
        initView();
        initListener();
        initData(getIntent());
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        initData(intent);
    }

    protected void initView() {
        imgAvatar = (ImageView) findViewById(R.id.img_avatar);
        tvName = (TextView) findViewById(R.id.tv_name);
        tvGender = (TextView) findViewById(R.id.tv_gender);
        tvBirthday = (TextView) findViewById(R.id.tv_birthday);

        mPhoneLayout = (LinearLayout) findViewById(R.id.ll_phone);

        tvIdCard = (TextView) findViewById(R.id.tv_id_title);
        tvIdCode = (TextView) findViewById(R.id.tv_id_code);
        imgIdVisible = (ImageView) findViewById(R.id.img_id_visible);

        tvEmail = (TextView) findViewById(R.id.tv_email);

        tvStatus = (TextView) findViewById(R.id.tv_custom_type);
        tvLevel = (TextView) findViewById(R.id.tv_custom_level);
        tvArea = (TextView) findViewById(R.id.tv_custom_area);
        tvAddr = (TextView) findViewById(R.id.tv_custom_addr);
        tvRemark = (TextView) findViewById(R.id.tv_custom_remark);

        mGridView = (GridView) findViewById(R.id.photo_gridview);
        mAdapter = new CustomInfoPhotoPreViewAdapter(this);
        mGridView.setAdapter(mAdapter);
    }

    protected void initListener() {
        mGridView.setOnItemClickListener(this);
        imgIdVisible.setOnClickListener(this);
    }

    protected void initData(Intent intent) {
        mCustom = (Custom) intent.getSerializableExtra(BundleKey.PARAM_CUSTOM);
        setData();

        ToastUtil.showLoading(this, getString(R.string.loading_data));
        //获取相片(有可能多张)
        CustomerController.showPhotosList(mCustom.customerId);
    }

    @Override
    protected void rightAction() {
        super.rightAction();
        if (mCustom != null)
            CustomEditOrAddActivity.launch(this, mCustom, mAdapter.getItems());
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.img_id_visible:
                isShowIdCode = !isShowIdCode;
                setIdCode();
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position == mAdapter.getItems().size())
            PhotoUtils.pickPhoto(CustomInfoActivity.this, Constants.MAX_VALUE_PHOTOS - mAdapter.getItems().size());
    }

    /* 监听获取相册返回的信息 */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPhotosListEvent(PhotosListEvent event) {
        ToastUtil.hideLoading();

        switch (event.state) {
            case PhotosListEvent.SUCC:
                if (event != null && event.data != null)
                    setPhotoItems(event.data.getAttachements());
                break;
            case PhotosListEvent.FAIL:
                ToastUtils.toastMessage(CustomInfoActivity.this, "获取照片失败,请稍后重试");
                break;
        }
    }

    public void setData() {
        if (mCustom == null)
            return;

        tvName.setText(mCustom.name);
        if (StringUtils.isNotEmpty(mCustom.avatar))
            imgAvatar.setImageURI(Uri.parse(mCustom.avatar));

        //客户性别
        switch (mCustom.gender) {
            case Custom.CUSTOM_GENDER_MAN:
                tvGender.setText(getString(R.string.custom_gender_man));
                tvName.setMaxWidth(AndroidUtils.getWindowWidth(this) - getResources().getDimensionPixelOffset(R.dimen.dp_150));
                break;
            case Custom.CUSTOM_GENDER_WOMAN:
                tvGender.setText(getString(R.string.custom_gender_woman));
                tvName.setMaxWidth(AndroidUtils.getWindowWidth(this) - getResources().getDimensionPixelOffset(R.dimen.dp_150));
                break;
            default:
                tvGender.setText(getString(R.string.custom_gender_none));
                tvName.setMaxWidth(AndroidUtils.getWindowWidth(this) - getResources().getDimensionPixelOffset(R.dimen.dp_220));
                break;
        }

        //客户类型
        switch (mCustom.type) {
            case Custom.TYPE_UNSOLD_CUSTOMER:
                tvStatus.setText(getString(R.string.customer_unsold_text));
                break;
            case Custom.TYPE_SOLDED_CUSTOMER:
                tvStatus.setText(getString(R.string.custom_already_written));
                break;
            default:
                tvStatus.setText(getString(R.string.empty));//未设置
                break;
        }

        //客户层级
        switch (mCustom.category) {
            case Custom.CUSTOM_LEVEL_A:
                tvLevel.setText(getString(R.string.custom_A));
                break;
            case Custom.CUSTOM_LEVEL_B:
                tvLevel.setText(getString(R.string.custom_B));
                break;
            case Custom.CUSTOM_LEVEL_C:
                tvLevel.setText(getString(R.string.custom_C));
                break;
            case Custom.CUSTOM_LEVEL_D:
                tvLevel.setText(getString(R.string.custom_D));
                break;
            default:
                tvLevel.setText(getString(R.string.empty));
                break;
        }

        // 证件类型
        tvIdCard.setText(Custom.getIdCardStr(mCustom.idCard, CustomInfoActivity.this));

        setIdCode();
        tvEmail.setText(mCustom.email);

        if (StringUtils.isNotEmpty(mCustom.province))
            tvArea.setText(mCustom.province);
        if (StringUtils.isNotEmpty(mCustom.city))
            tvArea.setText(tvArea.getText() + "  " + mCustom.city);

        tvAddr.setText(mCustom.address);
        tvRemark.setText(mCustom.remark);

        mPhoneLayout.removeAllViews();
        if (mCustom.getContactInfos() != null && mCustom.getContactInfos().size() > 0) {
            for (ContactInfo phone : mCustom.getContactInfos()) {
                CustomInfoPhoneView phoneItem = new CustomInfoPhoneView(this);
                phoneItem.setPhone(phone);
                mPhoneLayout.addView(phoneItem);
            }
        } else {
            CustomInfoPhoneView phoneItem = new CustomInfoPhoneView(this);
            phoneItem.setEmptyPhone();
            mPhoneLayout.addView(phoneItem);
        }

        int mBirthType = mCustom.birthdayType;
        if (StringUtils.isNotEmpty(mCustom.birthday)) {
            Calendar mCBirthDate = Calendar.getInstance();
            mCBirthDate.setTimeInMillis(Long.parseLong(mCustom.birthday));

            if (mBirthType == DatePickerDialog.OnDateSetListener.TYPE_GREGORIAN_NO_YEAR
                    || mBirthType == DatePickerDialog.OnDateSetListener.TYPE_GREGORIAN_YEAR) {
                String bir;
                if (mBirthType == DatePickerDialog.OnDateSetListener.TYPE_GREGORIAN_YEAR)
                    bir = String.format(getString(R.string.custom_birthday_has_year), mCBirthDate.get(Calendar.YEAR), mCBirthDate.get(Calendar.MONTH) + 1, mCBirthDate.get(Calendar.DAY_OF_MONTH));
                else
                    bir = String.format(getString(R.string.custom_birthday_no_year), mCBirthDate.get(Calendar.MONTH) + 1, mCBirthDate.get(Calendar.DAY_OF_MONTH));
                tvBirthday.setText(String.format(getString(R.string.custom_birthday), bir));
            } else {
                Lunar lunar = new Lunar(mCBirthDate);
                if (mBirthType == DatePickerDialog.OnDateSetListener.TYPE_LUNAR_NO_YEAR)
                    tvBirthday.setText(String.format(getString(R.string.custom_birthday_lunar), lunar.toString()));
                else
                    tvBirthday.setText(String.format(getString(R.string.custom_birthday_lunar), lunar.getLunarString()));
            }
        } else {
            tvBirthday.setText(getString(R.string.custom_birthday_none));
        }
    }

    /* 设置证件号码 */
    private void setIdCode() {
        String idCode = mCustom.idCode;
        imgIdVisible.setVisibility(StringUtils.isEmpty(idCode) ? View.GONE : View.VISIBLE);

        if (StringUtils.isEmpty(idCode)) {
            tvIdCode.setText("");
            return;
        }

        if (isShowIdCode) {
            tvIdCode.setText(idCode);
            imgIdVisible.setImageResource(R.drawable.client_info_icon_visible);
        } else {
            switch (mCustom.idCard) {
                case Custom.CUSTOM_IDCODE_ID:
                    if (idCode.length() < 15)
                        tvIdCode.setText(idCode);
                    else
                        tvIdCode.setText(idCode.substring(0, 6) + "********" + idCode.substring(14));
                    imgIdVisible.setImageResource(R.drawable.client_info_icon_invisible);
                    break;
                default:
                    if (idCode.length() < 5)
                        tvIdCode.setText(idCode.replaceAll(".", "*"));
                    else {
                        tvIdCode.setText(idCode.substring(0, idCode.length() - 4) + "****");
                    }
                    imgIdVisible.setImageResource(R.drawable.client_info_icon_invisible);
                    break;
            }
        }
    }

    /* 设置图片 */
    private void setPhotoItems(List<PhotoInfo> photoInfos) {
        if (photoInfos != null && photoInfos.size() > 0) {
            mAdapter.setItems(photoInfos);
            mGridView.setVisibility(View.VISIBLE);
            findViewById(R.id.tv_photo_none).setVisibility(View.GONE);
        } else {
            mAdapter.clearItems();
            mGridView.setVisibility(View.GONE);
            findViewById(R.id.tv_photo_none).setVisibility(View.VISIBLE);
        }
    }
}
